package com.xinhe.web.service;

import com.xinhe.web.common.Result;
import com.xinhe.web.entity.RoleMenu;
import com.xinhe.web.reposity.AuthRoleMenuRepository;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Set;

@Service
public class RoleMenuService {
    @Autowired
    AuthRoleMenuRepository authRoleMenuRepository;


    @Transactional(rollbackFor = {Exception.class})
    public Result saveRoleMenu(Long roleId, Set<Long> menuIds) {
        authRoleMenuRepository.deleteByRoleId(roleId);
        if (CollectionUtils.isNotEmpty(menuIds)) {
            for (Long menuId : menuIds) {
                RoleMenu roleMenu = new RoleMenu();
                roleMenu.setMenuId(menuId);
                roleMenu.setRoleId(roleId);
                this.authRoleMenuRepository.save(roleMenu);
            }
        }
        return Result.ok();
    }

    public Result findById(Long roleMenuId) {
        return Result.ok(authRoleMenuRepository.findById(roleMenuId).get());
    }

    public Result delete(Long roleMenuId) {
        authRoleMenuRepository.deleteById(roleMenuId);
        return Result.ok();
    }
}
